package com.naton.common.ui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.naton.common.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 添加ViewModel
 * @param <VB>
 */
public abstract class BaseVMActivity<VB extends ViewBinding , VM extends BaseViewModel> extends BaseActivity<VB> {

    protected VM mViewModel;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewModel();
        initView();
    }

    private void initView() {
        //显示吐司
        mViewModel.getMToastMsg().observe(this , this::showToast);
        //显示和取消进度条
        mViewModel.getMShowProgress().observe(this , show ->{
            if (show){
                showProgress();
            }else {
                hideProgress();
            }
        });
    }

    /**
     * 初始化ViewMode
     */
    protected void initViewModel(){
        if (mViewModel == null){
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType){
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
            }else {
                //如果没指定泛型参数 则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) getActivityScopeViewModel(modelClass);
        }
    }

    protected <T extends BaseViewModel> T getActivityScopeViewModel(@NonNull Class<T> modelClass) {
        T t = new ViewModelProvider.NewInstanceFactory().create(modelClass);
        getLifecycle().addObserver(t);
        return t;
    }

    protected <T extends ViewModel> T getApplicationScopeViewModel(@NonNull Class<T> modelClass) {
        return ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()).create(
                modelClass);
    }
}